const axios = require('axios');
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, // 使用当前环境
});

const timeUtils = require('../utils/timeUtils');
const priceUnitUtils = require('../utils/PriceUnitUtils');
const rpcUtils = require('../utils/rpcUtils');
const {convertYuanToJiao, convertJiaoToYuanString} = require("../utils/PriceUnitUtils");

const db = cloud.database();
const _ = db.command; // 初始化数据库命令对象

async function xiXieCheckoutInit(request) {
  const {productId, schoolCode, openId} = request;

  // 初始化返回结果结构
  let result = {
    product: {
      productId: null,
      productTitle: null,
      productDesc: null,
      imageUrl: null,
      price: null,
      extInfo: null,
      userNoticeText: null,
      serviceConfigs: null
    },
    address: null,
    deliveryTimes: null,
    uploadImgRequiredSwitch: null,
    userInfoVo: null,
  };

  try {
    // 并发获取相关数据
    const [productRes, userRes, uploadImgRequiredSwitchRes] = await Promise.all([
      db.collection('product').where({ product_id: productId, available_address:schoolCode}).get(),
      db.collection('user').where({ out_user_id: openId }).get(),
      db.collection('config').where({ config_name: "uploadImgRequiredSwitch",product_id:productId,school_code:schoolCode })
          .orderBy("create_ts", "desc").limit(100).get(),
    ]);

    if (productRes.data.length === 0) {
      console.error("Product not found","productId", productId);
      return rpcUtils.genResp(404, "Product not found", null);
    }
    const productDoc = productRes.data[0];

    if (userRes.data.length === 0) {
      console.error("User not found","openId", openId);
      return rpcUtils.genResp(404, "User not found", null);
    }
    const userDoc = userRes.data[0];

    // 获取用户信息
    let userInfoVo = {};
    userInfoVo.phone = userDoc.phone;

    // 获取用户地址
    const userAddress = getAddress(userDoc);
    let addressVo = userAddress? {
      name: userAddress.contact_name,
      phone: userAddress.contact_phone,
      school: userAddress.address_desc,
      detail: userAddress.address_detail,
      schoolCode: userAddress.address_code,
    } : null;

    // 获取配送时间配置
    let {deliveryTimesVo:deliveryTimesVo,packageStations:packageStations,packageStationsVo:packageStationsVo} = await buildDeliveryTimesVo(productId,schoolCode);

    // 获取上传图片开关配置
    const uploadImgRequiredSwitch = uploadImgRequiredSwitchRes.data.length > 0 ? uploadImgRequiredSwitchRes.data[0].content : false;

    // 从 productDoc 中获取服务配置
    const productServiceConfigs = productDoc.service_configs || [];

    // 填充返回结果
    result.product = {
      productId: productDoc.product_id,
      productTitle: productDoc.product_title,
      productDesc: productDoc.product_desc,
      imageUrl: productDoc.image_url,
      price: productDoc.price,
      extInfo: productDoc.ext_info,
      userNoticeText: productDoc.user_notice_text,
      serviceConfigs: productServiceConfigs
    };
    result.address = addressVo;
    result.deliveryTimes = deliveryTimesVo;
    result.uploadImgRequiredSwitch = uploadImgRequiredSwitch;
    result.userInfoVo = userInfoVo;

    return rpcUtils.genResp(rpcUtils.codeEnum.SUCCESS, null, result);
  } catch (error) {
    console.error("Error in xiXieCheckoutInit:", error.stack || error);
    return rpcUtils.genResp(500, "Error processing request", null);
  }
}

async function kuaiDiDaiQuCheckoutInit(request) {
  const {productId, schoolCode, openId} = request;

  // 初始化返回结果结构
  let result = {
    product: {
      productId: null,
      productTitle: null,
      productDesc: null,
      imageUrl: null,
      price: null,
      extInfo: null,
      userNoticeText: null,
      serviceConfigs: null,
      packageStations:null,
    },
    address: null,
    deliveryTimes: null,
    uploadImgRequiredSwitch: null,
    userInfoVo: null,
  };

  try {
    // 并发获取相关数据
    const [productRes, userRes, uploadImgRequiredSwitchRes] = await Promise.all([
      db.collection('product').where({ product_id: productId, available_address:schoolCode}).get(),
      db.collection('user').where({ out_user_id: openId }).get(),
      db.collection('config').where({ config_name: "uploadImgRequiredSwitch",product_id:productId,school_code:schoolCode })
          .orderBy("create_ts", "desc").limit(100).get(),
    ]);

    if (productRes.data.length === 0) {
      console.error("Product not found","productId", productId);
      return rpcUtils.genResp(404, "Product not found", null);
    }
    const productDoc = productRes.data[0];

    if (userRes.data.length === 0) {
      console.error("User not found","openId", openId);
      return rpcUtils.genResp(404, "User not found", null);
    }
    const userDoc = userRes.data[0];

    // 获取用户信息
    let userInfoVo = {};
    userInfoVo.phone = userDoc.phone;

    // 获取用户地址
    const userAddress = getAddress(userDoc);
    let addressVo = userAddress? {
      name: userAddress.contact_name,
      phone: userAddress.contact_phone,
      school: userAddress.address_desc,
      detail: userAddress.address_detail,
      schoolCode: userAddress.address_code,
    } : null;

    // 获取配送时间配置
    let {deliveryTimesVo:deliveryTimesVo,packageStations:packageStations,packageStationsVo:packageStationsVo} = await buildDeliveryTimesVo(productId,schoolCode);

    // 获取上传图片开关配置
    const uploadImgRequiredSwitch = uploadImgRequiredSwitchRes.data.length > 0 ? uploadImgRequiredSwitchRes.data[0].content : false;

    // 从 productDoc 中获取服务配置
    const productServiceConfigs = productDoc.service_configs || [];

    // 填充返回结果
    result.product = {
      productId: productDoc.product_id,
      productTitle: productDoc.product_title,
      productDesc: productDoc.product_desc,
      imageUrl: productDoc.image_url,
      price: productDoc.price,
      extInfo: productDoc.ext_info,
      userNoticeText: productDoc.user_notice_text,
      serviceConfigs: productServiceConfigs,
      packageStations: packageStationsVo,
    };
    result.address = addressVo;
    result.deliveryTimes = deliveryTimesVo;
    result.uploadImgRequiredSwitch = uploadImgRequiredSwitch;
    result.userInfoVo = userInfoVo;

    return rpcUtils.genResp(rpcUtils.codeEnum.SUCCESS, null, result);
  } catch (error) {
    console.error("Error in xiXieCheckoutInit:", error.stack || error);
    return rpcUtils.genResp(500, "Error processing request", null);
  }
}

async function checkout(request) {
  const wxContext = cloud.getWXContext();
  let { productId, count,
    participantId, userId, schoolCode,
    packagePickupInfos,
    printInfo,
    serviceConfigs} = request; // 入参已改为驼峰命名
  const openId = userId || wxContext.OPENID;
  packagePickupInfos = packagePickupInfos || [];
  printInfo = printInfo || {};
  serviceConfigs = serviceConfigs || [];
  packagePickupInfos = packagePickupInfos.filter(
    (info) => info.pickupAddress && info.pickupAddress.trim() !== ""
  );

  try {
    // 并发获取相关数据
    const [productRes, userRes, bargainRes, couponRes, schoolCouponPackageConfigsRes,uploadImgRequiredSwitchRes] = await Promise.all([
      db.collection('product').where({ product_id: productId, available_address:schoolCode}).get(),
      db.collection('user').where({ out_user_id: openId }).get(),
      participantId
          ? db.collection('bargain_record').where({participant_id: participantId }).get()
          : Promise.resolve({ data: [] }),
      db.collection('coupon_record').where({ out_user_id: openId })
          .orderBy("create_ts", "desc").limit(100).get(),
      schoolCode
          ? db.collection('coupon_config').where({ available_address: _.in([schoolCode])}).get()
          : Promise.resolve({ data: [] }),
      db.collection('config').where({ config_name: "uploadImgRequiredSwitch",product_id:productId,school_code:schoolCode })
          .orderBy("create_ts", "desc").limit(100).get(),
    ]);
    if (productRes.data.length === 0) {
      console.error("Product not found","productId", productId);
      return { code: 404, message: "Product not found" };
    }
    const productDoc = productRes.data[0];
    if (userRes.data.length === 0) {
      console.error("User not found","openId", openId);
      return { code: 404, message: "User not found" };
    }
    const userDoc = userRes.data[0];
    let userInfoVo = {};
    userInfoVo.phone = userDoc.phone;
    const userAddress = getAddress(userDoc);
    const bargainDoc = bargainRes.data[0];
    const couponDocs = couponRes.data;
    const uploadImgRequiredSwitch = uploadImgRequiredSwitchRes.data.length > 0 ? uploadImgRequiredSwitchRes.data[0].content : false;
    //最新的券包
    const schoolCouponPackageConfigDoc = schoolCouponPackageConfigsRes.data.length > 0
        ? schoolCouponPackageConfigsRes.data.reduce((max, current) =>
            current.coupon_package_version > max.coupon_package_version ? current : max
        )
        : null;

    let {deliveryTimesVo:deliveryTimesVo,packageStations:packageStations,packageStationsVo:pacakgeStationsVo} = await buildDeliveryTimesVo(productId,schoolCode);

    const productAmount = await computeProductAmount(count, productDoc,
      packagePickupInfos,packageStations, printInfo, serviceConfigs);

    const deliveryAmount = productDoc.delivery_amount; // 固定值
    const totalAmount = productAmount + deliveryAmount;

    const { discountAmount, discountList } = await computeDiscountAmount(totalAmount, couponDocs, bargainDoc);
    const payAmount = totalAmount - discountAmount;

    // 转换价格为字符串
    const priceDetailsVo = {
      totalAmount: priceUnitUtils.convertJiaoToYuanString(totalAmount),
      discountAmount: priceUnitUtils.convertJiaoToYuanString(discountAmount),
      discountList: discountList.map(item => ({
        ...item,
        description: item.desc,
        price: priceUnitUtils.convertJiaoToYuanString(item.price),
      })),
      payAmount: priceUnitUtils.convertJiaoToYuanString(payAmount),
      deliveryAmount: priceUnitUtils.convertJiaoToYuanString(deliveryAmount)
    };

    let schoolCouponPackageToClaimVo = null;
    let schoolCouponPackageClaimedVo = null;
    if (schoolCouponPackageConfigDoc) {
      const couponsHasClaimed = couponsFromCurVersionPackageConfig(couponDocs,schoolCouponPackageConfigDoc);
      const schoolCouponPackageVo = buildCouponPackageVo(schoolCouponPackageConfigDoc)
      if (couponsHasClaimed.length > 0) {
        const expirationDate = new Date(couponsHasClaimed[0].claim_time);
        expirationDate.setDate(expirationDate.getDate() + parseInt(couponsHasClaimed[0].expiration_days, 10));
        schoolCouponPackageClaimedVo = {
          ...schoolCouponPackageVo,
          deadLine: timeUtils.formatDateToYY_MM_DD_HH_MM_SS(expirationDate),
          isActive: true,
        }
      } else {
        schoolCouponPackageToClaimVo = {
          ...schoolCouponPackageVo,
          isActive: false
        }
      }
    }
    let addressVo = userAddress? {
      name: userAddress.contact_name,
      phone: userAddress.contact_phone,
      school: userAddress.address_desc,
      detail: userAddress.address_detail,
      schoolCode: userAddress.address_code,
    } : null;

    let packagePickupInfosDTO = packagePickupInfos? packagePickupInfos.map(info => ({
          pickup_address: info.pickupAddress,
          pickup_code: info.pickupCode,
          pickup_size: info.pickupSize,
          photos: info.photos || [],
      }))
    : null;

    let printInfoDTO = printInfo? {
          file_url: printInfo.fileUrl,
          printing_sides: printInfo.printingSides,
          printing_pages: printInfo.printingPages,
      }
    : null;

    // 从 productDoc 中获取服务配置
    const productServiceConfigs = productDoc.service_configs || [];

    // 生成订单数据
    const orderData = {
      out_trade_no: `T${Date.now()}`, // 交易号
      order_id: `O${Date.now()}`, // 订单号
      order_item: {
        product_id: productDoc.product_id,
        quantity: count,
      },
      total_amount: priceDetailsVo.totalAmount,
      discount_amount: priceDetailsVo.discountAmount,
      pay_amount: priceDetailsVo.payAmount,
      address: addressVo,
      create_ts: new Date(),
      update_ts: new Date(),
      order_status: "待支付",
      process_status: "待处理",
      out_user_id: openId,
      coupon_id: discountList.find((item) => item.discountType === "coupon")?.couponId || "",
      coupon_inner_id: discountList.find((item) => item.discountType === "coupon")?.innerId || "", // 保存 innerId 到快照
      participant_id: participantId || "",
      deliver_out_user_id: "",
      deliver_time: "",
      before_cleaning_photos: [],
      after_cleaning_photos: [],
      complaint_info: null,
      package_pickup_infos: packagePickupInfosDTO,
      print_info: printInfoDTO,
      service_configs: serviceConfigs // 保存服务配置到订单
    };

    // 保存订单快照
    const snapshotId = await saveOrderSnapshot(orderData);

    return {
      code: 200,
      message: "success",
      data: {
        snapshotId, // 返回快照表中的 ID
        product: {
          productId: productDoc.product_id,
          productTitle: productDoc.product_title,
          productDesc: productDoc.product_desc,
          imageUrl: productDoc.image_url,
          price: productDoc.price,
          extInfo: productDoc.ext_info,
          userNoticeText: productDoc.user_notice_text,
          serviceConfigs: productServiceConfigs // 从 productDoc 中获取服务配置
        },
        coupon: schoolCouponPackageToClaimVo || schoolCouponPackageClaimedVo,
        address: addressVo,
        price: priceDetailsVo,
        deliveryTimes: deliveryTimesVo,
        packageStations:pacakgeStationsVo,
        uploadImgRequiredSwitch:uploadImgRequiredSwitch,
        userInfoVo:userInfoVo,
      },
    };
  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message,
    };
  }
}     

async function buildDeliveryTimesVo(productId, schoolCode) {
  const deliveryTimeConfigRes = await db.collection('config')
    .where({
      config_name: "deliverTime",
      product_id: productId,
      school_code: schoolCode,
    })
    .get();

  if (!deliveryTimeConfigRes.data || deliveryTimeConfigRes.data.length === 0) {
    throw new Error("未找到对应的配送时间配置");
  }

  const deliveryTimeDoc = deliveryTimeConfigRes.data[0];
  let deliveryTimesVo = [];
  let deliveryTimeConfig = deliveryTimeDoc.content;
  let packageStations = deliveryTimeDoc.content.packageStations;
  let packageStationsVo = [];
  if (packageStations) {
    packageStationsVo = packageStations.map(item => item.station_name);
  }
  deliveryTimeConfig.dayOffsets.forEach((dayOffset) => {
    if(dayOffset == 0) {
      const futureTimeFrames = filterFutureTimeFrames(deliveryTimeConfig.timeFrames);
      if (futureTimeFrames) {
        let todayDeliveryTimeVo = {};
        todayDeliveryTimeVo.dayOffset = 0;
        todayDeliveryTimeVo.dateStr = '今天';
        todayDeliveryTimeVo.timeFrames = futureTimeFrames;
        deliveryTimesVo.push(todayDeliveryTimeVo);
      }
      return;
    }
    let deliveryTimeVo = { dayOffset: null, dateStr: null, timeFrames: [] };
    deliveryTimesVo.push(deliveryTimeVo);
    deliveryTimeVo.dayOffset = dayOffset;
    deliveryTimeVo.timeFrames = deliveryTimeConfig.timeFrames;

    // Calculate the date based on the dayOffset in Beijing Time (UTC+8)
    const currentDate = new Date();
    const targetDate = new Date(currentDate.getTime() + dayOffset * 24 * 60 * 60 * 1000 + 8 * 60 * 60 * 1000);

    // Get components of the target date
    const year = targetDate.getUTCFullYear();
    const month = String(targetDate.getUTCMonth() + 1).padStart(2, "0");
    const day = String(targetDate.getUTCDate()).padStart(2, "0");
    const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const weekDayStr = weekDays[targetDate.getUTCDay()];

    // Format dateStr based on dayOffset
    if (dayOffset === 0) {
      deliveryTimeVo.dateStr = `今天(${weekDayStr})`;
    } else if (dayOffset === 1) {
      deliveryTimeVo.dateStr = `明天(${weekDayStr})`;
    } else {
      deliveryTimeVo.dateStr = `${year}/${month}/${day}(${weekDayStr})`;
    }
  });

  return {deliveryTimesVo,packageStations,packageStationsVo};
}

// 筛选出时间点大于当前时间的时间段
function filterFutureTimeFrames(timeFrames) {
  // 获取当前时间并转换为东八区时间
  const now = new Date();

  // 获取 UTC 时间的时间戳
  const utcTimestamp = now.getTime() + now.getTimezoneOffset() * 60 * 1000;

  // 转换为东八区时间
  const eastEightTimestamp = utcTimestamp + 8 * 60 * 60 * 1000;
  const eastEightTime = new Date(eastEightTimestamp);

  const currentHours = eastEightTime.getHours();
  const currentMinutes = eastEightTime.getMinutes();

  // 筛选逻辑
  const filteredTimeFrames = timeFrames.filter((timeFrame) => {
    const [start, end] = timeFrame.split("-"); // 拆分时间段，取起始时间
    const [endHour, endMinute] = end.split(":").map(Number); // 转换为数字

    // 比较时间
    return (
      endHour > currentHours || (endHour === currentHours && endMinute > currentMinutes)
    );
  });

  return filteredTimeFrames;
}

// 工具函数：获取用户的默认地址
function getAddress(user) {
  const addresses = user.ext_info ? user.ext_info.address : null;
  if (!addresses || addresses.length === 0) return null;

  // 找到默认地址
  const defaultAddress = addresses.find(addr => addr.is_default === true || addr.is_default === "true");
  return defaultAddress || addresses[0];
}

// 计算优惠券折扣
function computeCouponDiscount(amountLeft, coupons) {
  if (!coupons || coupons.length === 0) return null;
  const now = new Date();
  // 筛选未过期的优惠券
  const validCoupons = coupons.filter(coupon => {
    const expirationDate = new Date(coupon.claim_time);
    expirationDate.setDate(expirationDate.getDate() + parseInt(coupon.expiration_days, 10));
    const notExpire = expirationDate.getTime() > now.getTime();
    const leftQtyGt0 = (coupon.quantity - (coupon.used_quantity || 0)) > 0;
    return notExpire && leftQtyGt0;
  });
  if (validCoupons.length === 0) return null;
  // 按金额升序排序
  validCoupons.sort((a, b) => priceUnitUtils.convertYuanToJiao(a.price) - priceUnitUtils.convertYuanToJiao(b.price));
  // 找到大于等于 amountLeft 的最小优惠券
  let selectedCoupon = validCoupons.find(coupon => priceUnitUtils.convertYuanToJiao(coupon.price) >= amountLeft);
  // 如果没有大于等于 amountLeft 的优惠券，选择最接近的优惠券
  if (!selectedCoupon) {
    selectedCoupon = validCoupons.reduce((closest, coupon) => {
      const couponPrice = priceUnitUtils.convertYuanToJiao(coupon.price);
      const closestPrice = priceUnitUtils.convertYuanToJiao(closest.price);
      return Math.abs(couponPrice - amountLeft) < Math.abs(closestPrice - amountLeft)
          ? coupon
          : closest;
    });
  }
  return selectedCoupon || null;
}

function computeProductAmount(count, productDoc, packagePickupInfos, packageStations, printInfo, serviceConfigs) {
  let totalAmount = 0;
  // 1. 打印产品优先判断
  if (productDoc.product_id === 'PPrintBlackAndWhite') {
    totalAmount = priceUnitUtils.convertYuanToJiao(productDoc.price) * parseInt(printInfo.printingPages) * count;
  } else if (productDoc.product_id === 'PPacakgePickUp') {
    // 2. 快递代取产品专门计算逻辑
    if (serviceConfigs && serviceConfigs.length > 0) {
      // 有服务配置的情况：serviceConfigs.selectedService.price * serviceConfigs.quantity + packageStations.[x].station_base_price
      serviceConfigs.forEach(serviceConfig => {
        if (serviceConfig && serviceConfig.selectedService && serviceConfig.selectedService.price) {
          const servicePrice = parseFloat(serviceConfig.selectedService.price) || 0;
          const quantity = parseInt(serviceConfig.quantity) || 1;
          totalAmount += priceUnitUtils.convertYuanToJiao(servicePrice.toString()) * quantity;
        }
      });
      
      // 根据 packagePickupInfos 中的 pickupAddress 匹配 packageStations 并加上基础费用
      if (packagePickupInfos && packagePickupInfos.length > 0 && packageStations && packageStations.length > 0) {
        packagePickupInfos.forEach(pickupInfo => {
          const matchingStation = packageStations.find(station => 
            station.station_name === pickupInfo.pickupAddress
          );
          if (matchingStation && matchingStation.station_base_price) {
            const basePrice = parseFloat(matchingStation.station_base_price) || 0;
            totalAmount += priceUnitUtils.convertYuanToJiao(basePrice.toString());
          }
        });
      }
    } else {
      // 没有服务配置的情况：只计算 packageStations.[x].station_base_price
      if (packagePickupInfos && packagePickupInfos.length > 0 && packageStations && packageStations.length > 0) {
        packagePickupInfos.forEach(pickupInfo => {
          const matchingStation = packageStations.find(station => 
            station.station_name === pickupInfo.pickupAddress
          );
          if (matchingStation && matchingStation.station_base_price) {
            const basePrice = parseFloat(matchingStation.station_base_price) || 0;
            totalAmount += priceUnitUtils.convertYuanToJiao(basePrice.toString());
          }
        });
      }
    }
  } else if (serviceConfigs && serviceConfigs.length > 0) {
    // 3. 其他服务类产品走服务配置
    serviceConfigs.forEach(serviceConfig => {
      if (serviceConfig && serviceConfig.selectedService && serviceConfig.selectedService.price) {
        const price = parseFloat(serviceConfig.selectedService.price) || 0;
        const quantity = parseInt(serviceConfig.quantity) || 1;
        totalAmount += priceUnitUtils.convertYuanToJiao(price.toString()) * quantity;
      }
    });
  } else {
    // 4. 兜底：普通商品
    totalAmount = priceUnitUtils.convertYuanToJiao(productDoc.price) * parseInt(count);
  }
  return totalAmount;
}

// 计算总折扣金额
async function computeDiscountAmount(totalAmount, couponDocs, bargainDoc) {
  let discountAmount = 0;
  let discountList = [];

  let amountLeft = totalAmount;
  // 计算砍价折扣
  if (bargainDoc) {
    const bargainDetailsRes = await db.collection('bargain_detail').where({
      participant_id: bargainDoc.participant_id,
    }).get();
    if(bargainDetailsRes != null) {
      let bargainDiscount = bargainDetailsRes.data.reduce((sum, item) => {
        const helpPriceInJiao = priceUnitUtils.convertYuanToJiao(item.help_price);
        return sum + helpPriceInJiao;
      }, 0);
      if (bargainDiscount > 0) {
        if (bargainDiscount >= amountLeft) bargainDiscount = amountLeft;
        discountList.push({ desc: "朋友帮砍", price: bargainDiscount, discountType:"bargain", participantId:bargainDoc.participant_id });
        amountLeft -= bargainDiscount;
        discountAmount += bargainDiscount;
      }
    }
  }
  // 计算优惠券折扣
  if (amountLeft > 0) {
    const mostNearCoupon = computeCouponDiscount(amountLeft, couponDocs);
    if (mostNearCoupon) {
      let couponDiscount = priceUnitUtils.convertYuanToJiao(mostNearCoupon.price);
      if (couponDiscount >= amountLeft) couponDiscount = amountLeft;
      discountList.push({ desc: "优惠券", price: couponDiscount, couponId: mostNearCoupon.coupon_id, couponPackageId: mostNearCoupon.coupon_package_id, discountType:"coupon", innerId:mostNearCoupon._id});
      amountLeft -= couponDiscount;
      discountAmount += couponDiscount;
    }
  }
  return { discountAmount, discountList };
}

function couponsFromCurVersionPackageConfig(couponDocs, schoolCouponPackageConfigDoc) {
  // 解构出筛选条件
  const { coupon_package_id, coupon_package_version } = schoolCouponPackageConfigDoc;
  // 筛选 couponDocs，符合条件的返回
  return couponDocs.filter(couponDoc =>
      couponDoc.coupon_package_id === coupon_package_id &&
      couponDoc.coupon_package_version === coupon_package_version
  );
}

/**
 * 构建优惠券包 VO 对象
 *
 * @param {Object} schoolCouponPackageConfigDoc - 优惠券包配置文档
 * @returns {Object} - 构建的优惠券包 VO 对象
 */
function buildCouponPackageVo(schoolCouponPackageConfigDoc) {
  // 计算 price: coupon_items 中所有元素的 price * quantity 的和 (以角为单位)
  const totalPriceInJiao = schoolCouponPackageConfigDoc.coupon_items.reduce((sum, item) => {
    const priceInJiao = priceUnitUtils.convertYuanToJiao(item.price); // 调用 convertYuanToJiao 转换为角
    return sum + priceInJiao * item.quantity;
  }, 0);
  // 构建返回对象
  return {
    couponId: schoolCouponPackageConfigDoc.coupon_package_id, // 优惠券包 ID
    couponName: schoolCouponPackageConfigDoc.coupon_package_desc, // 优惠券包名称
    type: schoolCouponPackageConfigDoc.type, // 优惠券包类型
    price: priceUnitUtils.convertJiaoToYuanString(totalPriceInJiao),
    tips: schoolCouponPackageConfigDoc.tips, // 提示信息
  };
}

/**
 * 将订单数据生成快照并存入快照表
 * @param {Object} snapshotData - 需要保存的快照数据
 * @returns {Promise<string>} - 返回保存成功的快照记录的 _id
 */
async function saveOrderSnapshot(snapshotData) {
  try {
    // 为快照数据添加时间戳
    const dataWithTimestamp = {
      ...snapshotData,
      snapshot_ts: new Date(), // 快照生成时间
    };

    // 插入快照数据到 `order_snapshot` 集合
    const snapshotRes = await db.collection("order_snapshot").add({
      data: dataWithTimestamp,
    });

    console.log("Snapshot saved successfully:", JSON.stringify(dataWithTimestamp));
    return snapshotRes._id; // 返回快照记录的 _id
  } catch (error) {
    console.error("Failed to save snapshot:", error);
    throw new Error("Failed to save order snapshot");
  }
}
//paotui checkout页面初始化
async function paoTuiCheckOut(request) {
  const { productId,schoolCode, openId} = request;

  let productDocPromise = db.collection('product').where({ product_id: productId, available_address:schoolCode}).get();
  const [productRes] = await Promise.all([productDocPromise]);

  const productDoc = productRes.data[0];
  const productServiceConfigs = productDoc.service_configs || []

  // 转换价格为字符串
  let priceDetailsVo = {
    totalAmount: productDoc.price,
    discountAmount: "0",
    discountList: [],
    payAmount: productDoc.price,
    deliveryAmount: "0"
  };

  return {
    code: 200,
    message: "success",
    data: {
      product: {
        productId: productDoc.product_id,
        productTitle: productDoc.product_title,
        productDesc: productDoc.product_desc,
        imageUrl: productDoc.image_url,
        price: productDoc.price,
        userNoticeText: productDoc.user_notice_text,
        serviceConfigs: productServiceConfigs // 从 productDoc 中获取服务配置
      },
      price: priceDetailsVo
    }
  }
}

async function paoTuiPriceCompute(request) {

  let data = {
    totalAmount: "0",
    payAmount: "0"
  };
  const { selectedServiceConfigs } = request;
  let total = 0;
  if (selectedServiceConfigs) {
    Object.values(selectedServiceConfigs).forEach(cfg => {
      if (cfg.selectedService && cfg.selectedService.price) {
        const price = parseFloat(cfg.selectedService.price) || 0;
        const quantity = parseInt(cfg.quantity) || 1;
        total += price * quantity;
      }
    });
  }
  // 转为元，保留两位小数，字符串类型
  const totalYuan = total.toFixed(2);
  data.totalAmount = totalYuan;
  data.payAmount = totalYuan;
  return rpcUtils.genResp(200, "success", data);
}

async function computePriceForSelectedService(selectedServiceConfigs) {
  let result = {
    totalAmount: "0"
  };
  let total = 0;
  if (selectedServiceConfigs) {
    Object.values(selectedServiceConfigs).forEach(cfg => {
      if (cfg.selectedService && cfg.selectedService.price) {
        const price = parseFloat(cfg.selectedService.price) || 0;
        const quantity = parseInt(cfg.quantity) || 1;
        total += price * quantity;
      }
    });
  }
  // 转为元，保留两位小数，字符串类型
  const totalYuan = total.toFixed(2);
  result.totalAmount = totalYuan;
  return result;
}

async function computeBargainDiscount(participantId) {
  let discountAmount = 0;
  let discountList = [];
  
  if (participantId) {
    const bargainDetailsRes = await db.collection('bargain_detail').where({
      participant_id: participantId,
    }).get();
    
    if (bargainDetailsRes && bargainDetailsRes.data.length > 0) {
      let bargainDiscount = bargainDetailsRes.data.reduce((sum, item) => {
        const helpPriceInJiao = priceUnitUtils.convertYuanToJiao(item.help_price);
        return sum + helpPriceInJiao;
      }, 0);
      
      if (bargainDiscount > 0) {
        discountList.push({ desc: "朋友帮砍", price: convertJiaoToYuanString(bargainDiscount), discountType:"bargain", participantId:participantId });
        discountAmount = bargainDiscount;
      }
    }
  }
  
  return { discountAmount, discountList };
}

async function xiXiePriceCompute(request) {
  let result = {
    totalAmount: "0",
    discountAmount:"0",
    discountList:"0",
    deliveryAmount:"0",
    payAmount: "0",
  };
  const { productId, schoolCode, selectedServiceConfigs, participantId } = request;
  
  try {
    // 并发获取产品信息和计算服务配置总金额
    const productPromise = db.collection('product').where({ 
      product_id: productId, 
      available_address: schoolCode 
    }).get();
    
    const pricePromise = computePriceForSelectedService(selectedServiceConfigs);
    
    const [productInfo, priceResult] = await Promise.all([productPromise, pricePromise]);
    
    const productDoc = productInfo.data[0];
    const serviceAmountYuan = parseFloat(priceResult.totalAmount) || 0;
    const serviceAmount = priceUnitUtils.convertYuanToJiao(serviceAmountYuan.toString());

    // 获取配送费，如果没有设置则默认为0
    const deliveryAmount = productDoc.delivery_amount || 0;

    const totalAmount = serviceAmount + deliveryAmount;
    
    // 计算砍价折扣
    const { discountAmount, discountList } = await computeBargainDiscount(participantId);
    
    
    // 计算最终支付金额：总金额 + 配送费 - 折扣金额
    const payAmount = Math.max(serviceAmount + deliveryAmount - discountAmount,0);

    // 转换价格为字符串
    result.totalAmount = priceUnitUtils.convertJiaoToYuanString(totalAmount);
    result.discountAmount = priceUnitUtils.convertJiaoToYuanString(discountAmount);
    result.discountList = discountList;
    result.deliveryAmount = priceUnitUtils.convertJiaoToYuanString(deliveryAmount);
    result.payAmount = priceUnitUtils.convertJiaoToYuanString(payAmount);

    return rpcUtils.genResp(200, "success", result);
  } catch (error) {
    console.error("Error in xiXiePriceCompute:", error.stack || error);
    return rpcUtils.genResp(500, "Error processing request", null);
  }
}

// 打印结算初始化
async function printCheckoutInit(request) {
  const { productId, schoolCode, openId } = request;
  
  try {
    // 并发获取用户信息、商品信息
    const userPromise = db.collection('user').where({ out_user_id: openId }).get();
    const productPromise = db.collection('product').where({ product_id: productId, available_address: schoolCode }).get();
    
    const [userInfo, productInfo] = await Promise.all([userPromise, productPromise]);
    
    // 校验用户信息
    if (userInfo.data.length === 0) {
      return rpcUtils.genResp(500, "User not found", null);
    }
    
    // 校验商品信息
    if (productInfo.data.length === 0) {
      return rpcUtils.genResp(500, "Product not found", null);
    }
    
    const productDoc = productInfo.data[0];
    const userDoc = userInfo.data[0];
    
    // 获取用户地址
    const address = getAddress(userDoc);
    
    // 构建配送时间
    const { deliveryTimesVo: deliveryTimes } = await buildDeliveryTimesVo(productId, schoolCode);
    
    // 构建返回数据
    const data = {
      product: {
        productId: productDoc.product_id,
        productTitle: productDoc.product_title,
        productDesc: productDoc.product_desc,
        imageUrl: productDoc.image_url,
        price: productDoc.price,
        extInfo: productDoc.ext_info,
        userNoticeText: productDoc.user_notice_text,
        serviceConfigs: productDoc.service_configs || [],
      },
      address: address,
      deliveryTimes: deliveryTimes,
      userInfoVo: {
        openId: userDoc.out_user_id,
        nickName: userDoc.nick_name || '',
        avatarUrl: userDoc.avatar_url || ''
      }
    };
    
    return rpcUtils.genResp(200, "success", data);
  } catch (error) {
    console.error("Error in printCheckoutInit:", error.stack || error);
    return rpcUtils.genResp(500, "Error processing request", null);
  }
}

// 打印价格计算
async function printComputePrice(request) {
  let result = {
    totalAmount: "0",
    discountAmount: "0",
    discountList: "0",
    deliveryAmount: "0",
    payAmount: "0",
  };
  
  const { productId, schoolCode, selectedServiceConfigs, participantId, paperNum = 1, copyNum = 1 } = request;
  
  try {
    // 并发获取产品信息和计算服务配置总金额
    const productPromise = db.collection('product').where({
      product_id: productId,
      available_address: schoolCode
    }).get();
    const [productInfo] = await Promise.all([productPromise]);
    const productDoc = productInfo.data[0];
    // 计算基础服务价格
    const priceResult = await computePriceForSelectedService(selectedServiceConfigs);
    let serviceAmountYuan = parseFloat(priceResult.totalAmount) || 0;
    
    // 根据纸张数量和份数计算总价格
    const paperCount = parseInt(paperNum) || 1;
    const copyCount = parseInt(copyNum) || 1;
    serviceAmountYuan = serviceAmountYuan * paperCount * copyCount;

    const deliveryAmount = productDoc.delivery_amount || 0;

    const totalAmount = priceUnitUtils.convertYuanToJiao(serviceAmountYuan.toString()) + deliveryAmount;

    // 计算砍价折扣
    const { discountAmount, discountList } = await computeBargainDiscount(participantId);
    
    const payAmount = totalAmount - discountAmount;

    // 转换价格为字符串
    result.totalAmount = priceUnitUtils.convertJiaoToYuanString(totalAmount);
    result.discountAmount = priceUnitUtils.convertJiaoToYuanString(discountAmount);
    result.discountList = discountList;
    result.deliveryAmount = priceUnitUtils.convertJiaoToYuanString(deliveryAmount);
    result.payAmount = priceUnitUtils.convertJiaoToYuanString(payAmount);

    return rpcUtils.genResp(200, "success", result);
  } catch (error) {
    console.error("Error in printComputePrice:", error.stack || error);
    return rpcUtils.genResp(500, "Error processing request", null);
  }
}

async function kuaiDiDaiQuComputePrice(request) {
  const { productId, schoolCode, selectedServiceConfigs, participantId, pickupInputs} = request;
  let result = {
    totalAmount: "0",
    discountAmount: "0",
    discountList: [],
    deliveryAmount: "0",
    payAmount: "0",
  };
  
  try {
    // 获取产品信息
    const productPromise = db.collection('product').where({
      product_id: productId,
      available_address: schoolCode
    }).get();
    const [productInfo] = await Promise.all([productPromise]);
    const productDoc = productInfo.data[0];
    
    // 获取包裹站点信息
    let {deliveryTimesVo, packageStations, packageStationsVo} = await buildDeliveryTimesVo(productId, schoolCode);
    
    let totalAmount = 0;
    
    // 计算服务配置价格
    if (selectedServiceConfigs && selectedServiceConfigs.length > 0) {
      selectedServiceConfigs.forEach(serviceConfig => {
        if (serviceConfig && serviceConfig.selectedService && serviceConfig.selectedService.price) {
          const servicePrice = parseFloat(serviceConfig.selectedService.price) || 0;
          const quantity = parseInt(serviceConfig.quantity) || 1;
          totalAmount += priceUnitUtils.convertYuanToJiao(servicePrice.toString()) * quantity;
        }
      });
    }
    // 根据 pickupInputs 中的 stationName 匹配 packageStations 并加上基础费用
    if (pickupInputs && pickupInputs.length > 0 && packageStations && packageStations.length > 0) {
      pickupInputs.forEach(pickupInput => {
        const matchingStation = packageStations.find(station => 
          station.station_name === pickupInput.stationName
        );
        if (matchingStation && matchingStation.station_base_price) {
          const basePrice = parseFloat(matchingStation.station_base_price) || 0;
          totalAmount += priceUnitUtils.convertYuanToJiao(basePrice.toString());
        }
      });
    }

    const deliveryAmount = productDoc.delivery_amount || 0;
    totalAmount += deliveryAmount;

    // 计算砍价折扣
    const { discountAmount, discountList } = await computeBargainDiscount(participantId);
    
    const payAmount = totalAmount - discountAmount;

    // 转换价格为字符串
    result.totalAmount = priceUnitUtils.convertJiaoToYuanString(totalAmount);
    result.discountAmount = priceUnitUtils.convertJiaoToYuanString(discountAmount);
    result.discountList = discountList;
    result.deliveryAmount = priceUnitUtils.convertJiaoToYuanString(deliveryAmount);
    result.payAmount = priceUnitUtils.convertJiaoToYuanString(payAmount);

    return rpcUtils.genResp(200, "success", result);
  } catch (error) {
    console.error("Error in kuaiDiDaiQuComputePrice:", error.stack || error);
    return rpcUtils.genResp(500, "Error processing request", null);
  }
}

module.exports = {
  checkout: checkout,
  paoTuiPriceCompute: paoTuiPriceCompute,
  paoTuiCheckOut: paoTuiCheckOut,
  xiXiePriceCompute: xiXiePriceCompute,
  xiXieCheckoutInit: xiXieCheckoutInit,
  kuaiDiDaiQuCheckoutInit: kuaiDiDaiQuCheckoutInit,
  printCheckoutInit: printCheckoutInit,
  printComputePrice: printComputePrice,
  kuaiDiDaiQuComputePrice: kuaiDiDaiQuComputePrice
};